package com.neo.tiny.resolver;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.experimental.UtilityClass;

import java.util.List;
import java.util.stream.Collectors;


/**
 * @author yqz
 * @Description 分页数据DO --> VO
 * @CreateDate 2022/8/8 19:58
 */
@UtilityClass
public class CommonPage {

    public <DO, VO> Page<VO> restPage(IPage<DO> page, Class<VO> voClass) {

        Page<VO> voPage = new Page<>();
        BeanUtil.copyProperties(page, voPage);

        List<DO> records = page.getRecords();

        List<VO> list = records.stream().map(item -> BeanUtil.copyProperties(item, voClass)).collect(Collectors.toList());
        voPage.setRecords(list);

        return voPage;
    }

    /**
     * 将SpringData分页后的list转为分页信息
     */
    public static <DO, VO> IPage<VO> restPage(org.springframework.data.domain.Page<DO> pageInfo, Class<VO> voClass) {
        IPage<VO> page = new Page<>();

        page.setTotal(pageInfo.getTotalPages());
        page.setCurrent(pageInfo.getNumber());
        page.setSize(pageInfo.getSize());
        page.setTotal(pageInfo.getTotalElements());

        List<DO> content = pageInfo.getContent();

        List<VO> list = content.stream()
                .map(item -> BeanUtil.copyProperties(item, voClass)).collect(Collectors.toList());

        page.setRecords(list);
        return page;
    }

}
